package services.impl;





import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import constants.CommonConstant;
import services.ITokenService;
import utils.RedisUtil;
import utils.TokenUtil;

public class TokenServiceImpl implements ITokenService{
	
	private static Logger log = (Logger) LoggerFactory.getLogger(TokenServiceImpl.class);
	private static String TOKEN_PASSWORD = "FujinG";
	private static String USER_TOKEN_PREFIX = "user";
	

	@Override
	public String createToken(String id) {
		long currentTime = System.currentTimeMillis();
		String content = new StringBuilder(USER_TOKEN_PREFIX).append(".")
				.append(id).append(".").append(currentTime).toString();
		return TokenUtil.encryptAccessToken(content,TOKEN_PASSWORD);
	}
	
	@Override
	public void deleteToken() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void resetToken() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public int checkToken(String token, RedisService redis) {
		// check the if token is generated by this system
		String content = TokenUtil.decrypt(token, TOKEN_PASSWORD);
		if(content==null){
			log.warn("This is not a recognizable token");
			return -2;
		}
		String[] strs = content.split("\\.");
		if(strs.length!=3||!strs[0].equals(USER_TOKEN_PREFIX)){
			log.warn("Illegal certification token");
			return -1;
		}
		// check this authorization ex or not
		String userId = strs[1];
		String _token = RedisUtil.get(redis, CommonConstant.AUTH_CACHE_KEY_PRE+userId);
		if(!token.equals(_token)){
			return 0;
		}
		// reset authorization ex if authorized pass
		RedisUtil.addCache(redis, RedisUtil.AUTHERIZE_CACHE_EX, CommonConstant.AUTH_CACHE_KEY_PRE+userId, token);
		return Integer.parseInt(userId);		
	}

	@Override
	public void getToken() {
		// TODO Auto-generated method stub
		
	}

}
